<?php
namespace app\index\model;

use app\sw\model\DepartmentModel;
use think\Model;

class UserModel extends Model{

    protected $name = 'sw_users';
    protected $pk = 'id';


    const ROLES_ARR = [
        "Admin" => '超级管理员',
        "KsAdmin" => '科室管理员',
    ];

    public $append = ['login_time_str', 'roles', 'roles_arr', 'login_time_status'];
    public $with = ['department'];

    public function getLoginTimeStrAttr(){
        // return date('Y-m-d H:i:s', $value);
        // 通过最后一次登录时间，格式化时间戳。转化为 刚刚、几分钟前、几小时前、几天前、几月前、几年前
        if($this->last_logintime == 0){
            return "从未登录";
        }
        $time = time() - $this->last_logintime;
        if($time < 60){
            return '刚刚';
        }else if($time < 3600){
            return floor($time / 60) . '分钟前';
        }else if($time < 86400){
            return floor($time / 3600) . '小时前';
        }else if($time < 2592000){
            return floor($time / 86400) . '天前';
        }else if($time < 31104000){
            return floor($time / 2592000) . '月前';
        }else{
            return floor($time / 31104000) . '年前';
        }
    }



    public function getRolesAttr(){
        return explode(',', $this->role);
    }


    public function department(){
        return $this->hasOne(DepartmentModel::class, 'id', 'dept_id');
    }
    
    public function getRolesArrAttr(){

        $roles = explode(',', $this->role);
        $result = [];

        foreach($roles as $role){
            $roleName = self::ROLES_ARR[$role] ?? '';
            if($roleName) $result[] = $roleName;
        }
        return $result;
    }


    public function getLoginTimeStatusAttr(){
        // 通过最后登录时间，给登录状态一个颜色。60分钟内为 success 一天以内为 info 一周以内为 warning 一月以内为 danger
        $time = time() - $this->last_logintime;
        if($time < 3600){
            return 'success';
        }else if($time < 86400){
            return 'info';
        }else if($time < 604800){
            return 'warning';
        }else if($time < 2592000){
            return 'danger';
        }else{
            return 'default';
        }
    }

}